package utils;

import com.alibaba.fastjson.JSONObject;

public class UserManager {

    public static boolean userExists(String email) throws Exception {
        String sql = "SELECT * FROM users WHERE email='" + email + "'";
        JSONObject json = DatabaseUtils.executeQuery(sql);
        return json.size() > 0;
    }

    public static boolean userExists(String email, String passwordMD5) throws Exception {
        String sql = "SELECT * FROM users WHERE email='" + email + "' and password='" + passwordMD5 + "'";
        JSONObject json = DatabaseUtils.executeQuery(sql);
        return json.size() > 0;
    }

    public static void updateUserPassword(String email, String newPasswordMD5) throws Exception {
        String sql = "UPDATE users SET password='" + newPasswordMD5 + "' WHERE email='" + email + "'";
        DatabaseUtils.executeUpdate(sql);
    }

    public static void registerUser(String username, String email, String passwordMD5) throws Exception {
        String sql = "INSERT INTO users (username, email, password) VALUES ('" + username + "', '" + email + "', '" + passwordMD5 + "')";
        DatabaseUtils.executeUpdate(sql);
    }

    public static JSONObject getUsersInfoAsJson(int page, int limit) throws Exception {
        String sql = "SELECT id, username, email, password, role FROM users LIMIT " + (page - 1) * limit + "," + limit;

        JSONObject json = DatabaseUtils.executeQueryForArray(sql);

        // 将JSONObject转换为UTF-8编码的JSON
        return json;
    }
}